package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/23 9:09
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        Table table = tenv.fromDataStream(stream);
        tenv.createTemporaryView("sensor", table);
        
        // 1. 在table api中使用
        // 1.1 内联的方式
        /*table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")).as("vc_sum"))
            .execute()
            .print();*/
        
        // 1.2 注册后使用
        tenv.createTemporaryFunction("my_avg", MyAvg.class);
        /*table
            .groupBy($("id"))
            .select($("id"), call("my_avg", $("vc")).as("vc_sum"))
            .execute()
            .print();*/
        
        // 2. 在sql语句中使用
        // 2. 1先注册
        
        // 2.2 再使用
        tenv.sqlQuery("select " +
                          " id, " +
                          " my_avg(vc) " +
                          "from sensor " +
                          "group by id").execute().print();
        
        
    }
    
    public static class Avg {
        public Double sum = 0D;
        public Long count = 0L;
        
        public Double avg() {
            return sum / count;
        }
        
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
        
        // 返回聚合的最终结果
        @Override
        public Double getValue(Avg acc) {
            return acc.avg();
        }
        
        // 初始化累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        public void accumulate(Avg avg, Double vc) {
            avg.sum += vc;
            avg.count++;
        }
    }
    
}
